package com.key.w8.http1.connection.client;

import com.key.w8.http1.connection.connectionImpl.ClientHttp1PersistentConnection;
import com.key.w8.http1.entity.HttpRequest;
import com.key.w8.http1.entity.HttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;

/**
 * @Author: k8
 * @CreateTime: 2025-04-28
 * @Version: 1.0
 */
public class ShortConnection {
    ClientHttp1PersistentConnection persistentConnection;
    private ExecutorService executorService;

    public ShortConnection(ExecutorService executorService, ClientHttp1PersistentConnection persistentConnection) {
        this.executorService = executorService;
        this.persistentConnection = persistentConnection;
    }

    public HttpResponse writeRequestNeedResponseSync(HttpRequest httpRequest) throws ExecutionException, InterruptedException {
        if (!httpRequest.headers().contains(HttpHeaderNames.CONNECTION)){
            httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        }
        return this.persistentConnection.writeRequestNeedResponseSync(httpRequest);
    }
    public CompletableFuture<HttpResponse> writeRequestNeedResponse(HttpRequest httpRequest){
        if (!httpRequest.headers().contains(HttpHeaderNames.CONNECTION)){
            httpRequest.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        }
        if (executorService != null){
            return CompletableFuture.supplyAsync(()->{
                try {
                    return this.persistentConnection.writeRequestNeedResponseSync(httpRequest);
                } catch (ExecutionException | InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },executorService);
        }
        return CompletableFuture.supplyAsync(()->{
            try {
                return this.persistentConnection.writeRequestNeedResponseSync(httpRequest);
            } catch (ExecutionException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
